package com.iot08.admin.utils;

import java.io.FileInputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * @author cwj
 * @description
 * @date 2025/1/2 14:10
 **/
public class KeyUtils {

   /* public static PrivateKey loadPrivateKeyFromClasspath(String path) throws Exception {
        try (InputStream inputStream = KeyUtils.class.getClassLoader().getResourceAsStream(path)) {
            if (inputStream == null) {
                throw new IllegalArgumentException("Certificate file not found in classpath: " + path);
            }

            // 读取文件内容并进行 Base64 解码
            byte[] keyBytes = inputStream.readAllBytes();
            String privateKeyContent = new String(keyBytes)
                    .replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "")
                    .replaceAll("\\s+", "");

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] decodedKey = Base64.getDecoder().decode(privateKeyContent);
            return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decodedKey));
        }
    }*/

    public static PrivateKey loadPrivateKey(String privateKeyPath) throws Exception {
        byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyPath));
        String privateKeyContent = new String(keyBytes)
                .replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s+", "");

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.getDecoder().decode(privateKeyContent);
        return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decodedKey));
    }


    public static PrivateKey loadPrivateKeyFromPath(String privateKeyPath) throws Exception {
        // 读取私钥文件内容
        byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyPath));

        // 将私钥内容转换为字符串并去掉头尾的标识符
        String privateKeyContent = new String(keyBytes)
                .replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s+", ""); // 删除所有空格和换行

        // 使用 Base64 解码私钥内容
        byte[] decodedKey = Base64.getDecoder().decode(privateKeyContent);

        // 使用 KeyFactory 生成私钥
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }


    /**
     * @description 获取公钥
     * @author cwj
     * @param [certPath]
     * @return java.security.PublicKey
     * @date @time 2025/1/4 9:13
     **/
    public static PublicKey loadPublicKeyFromCert(String certPath) throws Exception {
        try (FileInputStream inputStream = new FileInputStream(certPath)) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate certificate = (X509Certificate) cf.generateCertificate(inputStream);
            return certificate.getPublicKey();
        }
    }

    public static void main(String[] args) throws Exception {
        // 假设你的私钥文件路径是 "path/to/your/private-key.pem"
        String privateKeyPath = "D:/project/project/project-1/eluxiangban-service/iot08-web-api/src/main/resources/cert/apiclient_key.pem";
        PrivateKey privateKey = loadPrivateKeyFromPath(privateKeyPath);

        System.out.println("Loaded Private Key: " + privateKey);
    }

}
